package com.example.myapplication.ui.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.example.myapplication.R;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/*保存用户名和密码的逻辑
 * 1.进入页面时，判断之前是否存储了用户名和密码
 *               1.存储了用户名和密码，获取数据，直接添加到EditText当中，并且checkbox为选中状态
 *               2.没有存储，EditText什么也不用填写，checkBox为未选中状态
 *
 * 2.点击登录按钮时，判断是否需要存储，需要存储就存，不需要就删除文件中的内容
 * */
public class LoginActivity extends AppCompatActivity {
    EditText nameEt,pwdEt;
    CheckBox saveCb;
    String filename = "user";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        nameEt = findViewById(R.id.login_et_name);
        pwdEt = findViewById(R.id.login_et_pwd);
        saveCb = findViewById(R.id.login_cb_save);
//        判断是否存储了用户名和密码
        String s = readDataFromFile(filename);
        if (TextUtils.isEmpty(s)) {
            saveCb.setChecked(false);
        }else{
            String[] msg = s.split(":");
            nameEt.setText(msg[0]);
            pwdEt.setText(msg[1]);
            saveCb.setChecked(true);
        }
    }
    /* 从指定路径下读取数据*/
    private String readDataFromFile(String filename) {
        String msg = "";
        try {
            FileInputStream fis = openFileInput(filename);
            int hasRead = 0;
            byte[]buf = new byte[1024];
            while(true){
                hasRead = fis.read(buf);
                if (hasRead == -1) {
                    break;
                }
                String s = new String(buf, 0, buf.length);
                msg = msg+s;
            }
        } catch (Exception e) {
            return msg;
        }

        return msg;
    }

    public void onClick(View view) {
        String name = nameEt.getText().toString();
        String pwd = pwdEt.getText().toString();
        if(TextUtils.isEmpty(name)||TextUtils.isEmpty(pwd)){
            Toast.makeText(this,"用户名和密码不能为空...",Toast.LENGTH_SHORT).show();
            return;
        }
//        判断checkbox是否为选中状态
        if (saveCb.isChecked()) {
            String msg = name+":"+pwd;
            writeDataToFile(msg);
        }else {
            writeDataToFile("");
        }

        Toast.makeText(this,"登录成功",Toast.LENGTH_SHORT).show();
        finish();
    }

    private void writeDataToFile(String msg) {
        try {
            FileOutputStream fos = openFileOutput(filename, MODE_PRIVATE);
            fos.write(msg.getBytes());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
